package com.example.administrator.ormlite_demoproject;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.example.administrator.ormlite_demoproject.db.bean.UserInfo;
import com.example.administrator.ormlite_demoproject.db.dao.UserDao;

import java.sql.SQLException;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends AppCompatActivity {

    private UserDao mUserDao;
    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = this;
        mUserDao = new UserDao();
    }


    @OnClick({R.id.btn01, R.id.btn03, R.id.btn02, R.id.btn04})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn01:
                try {
                    UserInfo userInfo = new UserInfo("lzz", "baoan", "nan");
                    mUserDao.getUserDao(mContext).create(userInfo);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn02:
                try {
                    mUserDao.getUserDao(mContext).deleteById(1); // userId
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn03:
                UserInfo userInfo = new UserInfo("chen", "xingdong", "女");
                userInfo.setUserId(4);
                try {
                    mUserDao.getUserDao(mContext).update(userInfo);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn04:
                try {
                    List<UserInfo> userInfos = mUserDao.getUserDao(mContext).queryForAll();

                    StringBuffer stringBuffer = new StringBuffer();

                    for (int i = 0; i < userInfos.size(); i++) {
                        stringBuffer.append(userInfos.get(i).toString()+"\n");
                    }

                    Toast.makeText(mContext,stringBuffer.toString(),Toast.LENGTH_LONG).show();

                } catch (SQLException e) {
                    e.printStackTrace();
                }

                break;
        }
    }
}
